import weakref
import pyglet
from pyglet.image import Animation
from pyglet.sprite import Sprite
from pyglet.gl import *
from pymunk import inf, Vec2d, Body, Circle, Poly
from util import *

class Baby(object):

    def __init__(self, index):
        self.position = Vec2d(0,0)
        if index < 1 or index > 9: index = 1
        frames = [animation_frame('graphics/baby%d_right1.png' % index, 65, 15, 0.2),
                  animation_frame('graphics/baby%d_right2.png' % index, 65, 15, 0.2),
                  animation_frame('graphics/baby%d_right3.png' % index, 65, 15, 0.2),]
        self.sprite_right = Sprite(Animation(frames))

        frames = [animation_frame('graphics/baby%d_left1.png' % index, 65, 15, 0.2),
                  animation_frame('graphics/baby%d_left2.png' % index, 65, 15, 0.2),
                  animation_frame('graphics/baby%d_left3.png' % index, 65, 15, 0.2),]
        self.sprite_left = Sprite(Animation(frames))

        self.sprite_held = make_sprite('graphics/baby%d_held.png' % index, 25, 10)
    
        self.body = Body(1, inf)
        self.body.position = (100, 300)

        # Attach shape for body.
        body_vertices = [(-35,0), (-35,45), (35,45), (35,0)]
        self.body_shape = Poly(self.body, body_vertices)
        self.body_shape.friction = 0.1
        self.body_shape.elasticity = 0.5
        self.body_shape.collision_type = 2
        self.body_shape.object = weakref.ref(self)

        self.change_state('crawl_right')

        self.map = None

    def destroy(self):
        del self.body_shape
        del self.body
        del self.map

    def get_body_and_shapes(self):
        return (self.body, self.body_shape)

    def draw(self):
        self.sprite.position = self.body.position
        self.sprite.draw()

    def change_state(self, state):
        self.state = state
        if self.state == 'crawl_right':
            self.sprite = self.sprite_right
        elif self.state == 'crawl_left':
            self.sprite = self.sprite_left
        elif self.state == 'held':
            self.sprite = self.sprite_held
        elif self.state == 'idle':
            pass

    def weight(self):
        return 20

    def update(self, dt):
        delta = Vec2d(0, 0)
        if self.state == 'crawl_right':
            delta += Vec2d(1, 0)
        elif self.state == 'crawl_left':
            delta += Vec2d(-1, 0)
        elif self.state == 'idle':
            pass
        elif self.state == 'held':
            pass

        if delta:
            self.body.apply_impulse(350*dt*delta)

    def turn_around(self):
        if self.state == 'crawl_right':
            self.change_state('crawl_left')
        elif self.state == 'crawl_left':
            self.change_state('crawl_right')
        
